import { Injectable } from '@nestjs/common'
import { PagerDto } from "@dto/public.dto";
import { HttpPageTemplate, HttpResTemplate, HttpResult } from "@libs/http.result";
import { Express } from "express";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { FileEntity } from "@entities/file.entity";
import { ParamsException } from "@exceptions";
import { format } from "@utils/date";
import * as fs from 'fs'

@Injectable()
export class FileService {
    constructor(
        @InjectRepository(FileEntity)
        private readonly fileRepository: Repository<FileEntity>) {
    }
    /**
     * 获取文件列表
     * @param params
     */
    async getFileList(params: PagerDto): Promise<HttpPageTemplate> {
        return HttpResult.pageData({
            total: 10,
            list: []
        })
    }

    /**
     * 文件上传
     */
    async updateFile(file: Express.Multer.File): Promise<HttpResTemplate> {
        console.log(file)
        const newFile = this.fileRepository.create({
            id: file['fileId'],
            suffix: file['suffix'],
            size: file.size,
            path: file['savePath'].replace(/\\/g, '/'), // 转换正反斜线，转换结果如："public/uploads/image/2020-04-08/123456789.jpg"
            originName: file.originalname,
            signHash: '123456666',
            name: file.filename,
            createBy: '张三',
            createTime: format(new Date())
        })
        const saveRes = await this.fileRepository.save(newFile)
        return HttpResult.success(saveRes)
    }

    /**
     * 下载文件
     * @param fileId
     */
    async download(fileId: number) {
        if (!fileId) {
            throw new ParamsException('文件id不能为空')
        }
        const file = await this.fileRepository.findOne({where: {id: fileId}})
        if (!file) throw new ParamsException('参数有误')
        const data = fs.readFileSync(file.path, 'utf8')
        return data
    }
}
